// API service for native fetch requests to axum backend
const API_BASE_URL = '/api';

interface RequestOptions extends RequestInit {
  params?: Record<string, string>;
}

class ApiService {
  private async request<T = any>(
    endpoint: string,
    options: RequestOptions = {}
  ): Promise<T> {
    const { params, ...fetchOptions } = options;

    let url = `${API_BASE_URL}${endpoint}`;
    if (params) {
      const searchParams = new URLSearchParams(params);
      url += `?${searchParams.toString()}`;
    }

    const response = await fetch(url, {
      headers: {
        'Content-Type': 'application/json',
        ...fetchOptions.headers,
      },
      ...fetchOptions,
    });

    if (!response.ok) {
      const error = await response.text();
      throw new Error(`API request failed: ${response.statusText} - ${error}`);
    }

    return response.json();
  }

  // Agent Management APIs
  async getAgents() {
    return this.request('/agents');
  }

  async createAgent(agent: Partial<{
    id: string;
    name: string;
    description: string;
    model?: string;
    system_prompt?: string;
    tools?: string[];
  }>) {
    return this.request('/agents', {
      method: 'POST',
      body: JSON.stringify(agent),
    });
  }

  async getAgent(id: string) {
    return this.request(`/agents/${id}`);
  }

  async deleteAgent(id: string) {
    return this.request(`/agents/${id}`, {
      method: 'DELETE',
    });
  }

  // MCP Service Management APIs
  async getMcpServices() {
    return this.request('/mcp/services');
  }

  async createMcpService(service: Partial<{
    id: string;
    name: string;
    command: string;
    args?: string[];
    env?: Record<string, string>;
  }>) {
    return this.request('/mcp/services', {
      method: 'POST',
      body: JSON.stringify(service),
    });
  }

  async getMcpService(id: string) {
    return this.request(`/mcp/services/${id}`);
  }

  async deleteMcpService(id: string) {
    return this.request(`/mcp/services/${id}`, {
      method: 'DELETE',
    });
  }

  // MCP Tool APIs
  async getMcpTools() {
    return this.request('/tools');
  }

  async executeMcpTool(toolName: string, args: Record<string, any>) {
    return this.request(`/tools/${toolName}/run`, {
      method: 'POST',
      body: JSON.stringify(args),
    });
  }

  // Chat APIs
  async prompt(promptData: {
    agent_id?: string;
    prompt: string;
    history?: Array<{ role: string; content: string }>;
  }) {
    return this.request('/rig/prompt', {
      method: 'POST',
      body: JSON.stringify(promptData),
    });
  }

  async chat(agentName: string, chatData: {
    prompt: string;
    history?: Array<{ role: string; content: string }>;
  }) {
    return this.request(`/agents/${agentName}/chat`, {
      method: 'POST',
      body: JSON.stringify(chatData),
    });
  }

  async streamChat(chatData: {
    agent_id?: string;
    prompt: string;
    history?: Array<{ role: string; content: string }>;
  }) {
    const response = await fetch(`${API_BASE_URL}/rig/stream-chat`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(chatData),
    });

    if (!response.ok) {
      throw new Error(`Stream request failed: ${response.statusText}`);
    }

    return response;
  }
  // Provider Configuration APIs
  async getProviders() {
    return this.request('/config/providers');
  }

  async upsertConfig(config: { key: string; value: any; is_secret: boolean }) {
    return this.request('/config/upsert', {
      method: 'POST',
      body: JSON.stringify(config),
    });
  }

  async readConfig(configQuery: { key: string; is_secret: boolean }) {
    return this.request('/config/read', {
      method: 'POST',
      body: JSON.stringify(configQuery),
    });
  }

  // Conversation APIs
  async getConversations(params?: { limit?: number; offset?: number }) {
    return this.request('/conversations', { params: params as Record<string, string> });
  }

  async createConversation(data: { title: string; agent_id?: number; metadata?: any }) {
    return this.request('/conversations', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  async getConversation(id: number) {
    return this.request(`/conversations/${id}`);
  }

  async updateConversation(id: number, data: { title?: string; metadata?: any }) {
    return this.request(`/conversations/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data),
    });
  }

  async deleteConversation(id: number) {
    return this.request(`/conversations/${id}`, {
      method: 'DELETE',
    });
  }

  // Message APIs
  async getMessages(conversationId: number, params?: { limit?: number; offset?: number }) {
    return this.request(`/conversations/${conversationId}/messages`, { 
      params: params as Record<string, string> 
    });
  }

  async createMessage(conversationId: number, data: { 
    role: string; 
    content: string; 
    status?: string; 
    metadata?: any 
  }) {
    return this.request(`/conversations/${conversationId}/messages`, {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  async updateMessage(id: number, data: { 
    content?: string; 
    status?: string; 
    metadata?: any 
  }) {
    return this.request(`/messages/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data),
    });
  }

  // Bookmark APIs
  async getBookmarks(params?: { 
    limit?: number; 
    offset?: number; 
    category?: string; 
    favorites_only?: boolean 
  }) {
    const searchParams: Record<string, string> = {};
    if (params?.limit) searchParams.limit = params.limit.toString();
    if (params?.offset) searchParams.offset = params.offset.toString();
    if (params?.category) searchParams.category = params.category;
    if (params?.favorites_only) searchParams.favorites_only = 'true';
    
    return this.request('/bookmarks', { params: searchParams });
  }

  async createBookmark(data: {
    title: string;
    prompt: string;
    description?: string;
    category?: string;
    tags?: string[];
    metadata?: any;
  }) {
    return this.request('/bookmarks', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  async getBookmark(id: number) {
    return this.request(`/bookmarks/${id}`);
  }

  async deleteBookmark(id: number) {
    return this.request(`/bookmarks/${id}`, {
      method: 'DELETE',
    });
  }

  async useBookmark(id: number) {
    return this.request(`/bookmarks/${id}/use`, {
      method: 'POST',
    });
  }

  async toggleBookmarkFavorite(id: number) {
    return this.request(`/bookmarks/${id}/favorite`, {
      method: 'POST',
    });
  }

  async searchBookmarks(query: string, limit?: number) {
    const params: Record<string, string> = { q: query };
    if (limit) params.limit = limit.toString();
    
    return this.request('/bookmarks/search', { params });
  }

  // Knowledge APIs
  async getKnowledgeItems(params?: { 
    limit?: number; 
    offset?: number; 
    item_type?: string 
  }) {
    const searchParams: Record<string, string> = {};
    if (params?.limit) searchParams.limit = params.limit.toString();
    if (params?.offset) searchParams.offset = params.offset.toString();
    if (params?.item_type) searchParams.item_type = params.item_type;
    
    return this.request('/knowledge', { params: searchParams });
  }

  async createKnowledgeItem(data: {
    title: string;
    content?: string;
    item_type: string;
    url?: string;
    file_path?: string;
    file_size?: number;
    mime_type?: string;
    tags?: string[];
    metadata?: any;
  }) {
    return this.request('/knowledge', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  async getKnowledgeItem(id: number) {
    return this.request(`/knowledge/${id}`);
  }

  async deleteKnowledgeItem(id: number) {
    return this.request(`/knowledge/${id}`, {
      method: 'DELETE',
    });
  }

  async searchKnowledgeItems(query: string, limit?: number) {
    const params: Record<string, string> = { q: query };
    if (limit) params.limit = limit.toString();
    
    return this.request('/knowledge/search', { params });
  }

}

export const apiService = new ApiService();
export default apiService;
